package com.spring.Controller;

import com.spring.Controller.Interface.UserController;
import com.spring.Entity.UserEntity;
import com.spring.Service.Interface.UserServie;
import com.spring.Util.MD5Util;
import com.spring.Util.RSAUtils;
import com.spring.Util.STATUS;
import jxl.read.biff.BiffException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
//import org.apache.shiro.SecurityUtils;
//import org.apache.shiro.authc.AuthenticationException;
//import org.apache.shiro.authc.IncorrectCredentialsException;
//import org.apache.shiro.authc.UnknownAccountException;
//import org.apache.shiro.authc.UsernamePasswordToken;
//import org.apache.shiro.subject.Subject;
//import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Arabira on 2016/8/4.
 */
@Controller
@RequestMapping("/user")
public class UserControllerImpl implements UserController {
    @Autowired
    private UserServie userServie;

    public Map prepare(Map map) {
        RSAPublicKey publicKey = RSAUtils.getDefaultPublicKey();
        map.put("modulus", new String(Hex.encodeHex(publicKey.getModulus().toByteArray())));
        map.put("exponent", new String(Hex.encodeHex(publicKey.getPublicExponent().toByteArray())));
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public Map logIn() {
        Map<String, Object> response = new HashMap<>();
        response = prepare(response);
        return response;
    }

   /*
    @ResponseBody
    @RequestMapping(value = "/loginTest", method = RequestMethod.POST)
    public Map logIn(String userName, String password, String verifycode, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        //password = RSAUtils.decryptStringByJs(password);
        System.out.println("key:" + password);
        *//*if (StringUtils.isBlank(userName) || StringUtils.isBlank(password) || StringUtils.isBlank(verifycode)) {
            response.put( "status", "error" );
            response.put("message", "用户名或密码或验证码不可为空");
            response = prepare(response);
            return response;
        }*//*
        *//*if (! CaptchaUtil.getInstance().validateCaptchaResponse(verifycode, session)) {
            response.put("message","验证码有误");
            response = prepare(response);
            return response;
        }*//*
        Subject loginCheck = SecurityUtils.getSubject();
        if (! loginCheck.isAuthenticated()) {
            String message = null;
            try {
                UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
                loginCheck.login(token);
                UserEntity userEntity = userServie.findByUserName(userName);
                session.setAttribute("SID", userEntity.getId());
                response.put("status", "ok");
                response.put("description", "登录成功");
                return response;
            }
            catch (IncorrectCredentialsException uie) {
                message = "密码或账户有误";
            }
            catch ( AuthenticationException ae ) {
                message = "未知错误，请联系技术人员";
            }

            if (message != null) {
                response = prepare(response);
                response.put( "status", "error" );
                response.put("description", message);
                return response;
            }
        }
        response.put( "username", userName );
        return response;
    }*/

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Map testLogin(UserEntity userEntity, HttpSession session, HttpServletRequest request) {
//        Map model =new HashMap
//        mode.put('list',userlist)//userlist是个Arraylist之类的
//
//        return new ModelAndView("page",model);
//
//        在jsp页面中使用jstl标签取出值以下自动循环取出每个值
//                <c:forEach items="${list}" var="user">
//                ${user.username}
//        ${user.password}
//        ${user.address.value}//可以去对象中的对象的值属性
//        http://www.itmmd.com/201411/228.html


        Map response = new HashMap();
        UserEntity check = userServie.findByUserName(userEntity.getUserName());
        System.out.println("key:" + MD5Util.calc(userEntity.getPassword()));
        String des = userServie.login(userEntity.getUserName(), userEntity.getPassword());
        if (StringUtils.isBlank(des)) {
            session.setAttribute("SID", check.getId());
            session.setAttribute("SName",check.getName());
            System.out.println(session.getAttribute("SID"));
            response.put("status", "ok");
            response.put("description", "登录成功");
        } else {
            response.put("status", "error");
            response.put("description", des);
        }
        return response;
    }

    @ResponseBody
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public Map<String, Object> logOut(HttpSession session, HttpServletRequest httpServletRequest) {
        Map<String, Object> response = new HashMap<String, Object>();
        if (!String.valueOf(session.getAttribute("SID")).equals("null")) {
            session.removeAttribute("SID");
            response.put("status", "ok");
            response.put("description", "注销成功");
        } else {
            response.put("status", "error");
            response.put("description", "已登出");
        }
        session.invalidate();
        return response;
    }

    //通过excel文件导入用户，excel文件必须为.xls，范例是doc文件夹中的工作簿1.xls
    @ResponseBody
    @RequestMapping(value = "/addExcel", method = RequestMethod.POST)
    public Map<String, Object> addUserExcel(MultipartFile file,HttpSession session, HttpServletRequest request) throws IOException, BiffException {
        Map<String, Object> response = new HashMap<String, Object>();
        if (file == null) {
            response.put("status", "empty");
            response.put("description", "提交文件为空");
            return response;
        }
        String message = userServie.addByExcel(file);

        if (StringUtils.isBlank(message)) {
            response.put("status", "ok");
            response.put("description", "导入用户成功");
        } else {
            response.put("status", "error");
            response.put("description", message);
        }
        return response;
    }

    //手动添加用户
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Map<String, Object> addUser(UserEntity userEntity, HttpServletRequest httpServletRequest) {
        Map<String, Object> response = new HashMap<String, Object>();
        if (StringUtils.isBlank(userEntity.getId())
                || StringUtils.isBlank(userEntity.getUserName())
                || StringUtils.isBlank(userEntity.getPassword())
                || StringUtils.isBlank(userEntity.getDepartment())) {
            response.put("status", "empty");
            response.put("description", "id或用户名或密码或职位为空");
            return response;
        }
        if (!userServie.checkUser(userEntity)) {
            response.put("status", "exists");
            response.put("description", "用户已存在");
            return response;
        }
        int status = userServie.addUser(userEntity);
        if (status == STATUS.SUCCESS) {
            response.put("status", "ok");
            response.put("description", "添加成功");
        }
        if (status == STATUS.FAIL) {
            response.put("status", "fail");
            response.put("description", "添加失败");
        }
        return response;
    }

    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Map<String, Object> updateUser(HttpSession session, String OA, String emailAddress, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<String, Object>();
        UserEntity userEntity;
        String userId = (String) session.getAttribute("SID");
        if (userId.equals("null")) {
            response.put("status", "refuse");
            response.put("description", "未登录");
            return response;
        }
        userEntity = userServie.findById(userId);
        if (userServie.checkUser(userEntity)) {
            response.put("status", "empty");
            response.put("description", "用户不存在");
            return response;
        }
        int status = userServie.updateUser(userEntity, OA, emailAddress);
        if (status == STATUS.SUCCESS) {
            response.put("status", "ok");
            response.put("description", "修改成功");
        } else if (status == STATUS.FORMAT_ERROR) {
            response.put("status", "error");
            response.put("description", "填写信息格式错误");
        }
        return response;
    }

    //修改密码
    @ResponseBody
    @RequestMapping(value = "/change", method = RequestMethod.POST)
    public Map<String, Object> changePassword(HttpSession session, String oldPassword, String newPassword, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        String userId = (String) session.getAttribute("SID");
        if (StringUtils.isBlank(userId)) {
            response.put("status", "refuse");
            response.put("description", "未登录");
            return response;
        }
        UserEntity check = new UserEntity();
        check.setId(userId);
        if (userServie.checkUser(check)) {
            response.put("status", "empty");
            response.put("description", "用户不存在");
            return response;
        }
        int status = userServie.changePassword(userId, oldPassword, newPassword);
        if (status == STATUS.SUCCESS) {
            response.put("status", "ok");
            response.put("description", "修改密码成功");
        } else {
            response.put("status", "fail");
            response.put("description", "修改密码失败，旧密码不正确！");
        }
        return response;
    }

    //通过ID查找用户信息
    @ResponseBody
    @RequestMapping(value = "/byId", method = RequestMethod.POST)
    public Map<String, Object> findById(HttpSession session, HttpServletRequest request) {
        UserEntity user = null;
        Map<String, Object> response = new HashMap<String, Object>();
        String userId = (String) session.getAttribute("SID");
        if (StringUtils.isBlank(userId)) {
            response.put("status", "refuse");
            response.put("description", "未登录");
            return response;
        }
        user = userServie.findById(userId);
        if (null != user) {
            user.setPassword("********");
            response.put("status", "ok");
            response.put("body", user);
        } else {
            response.put("status", "error");
            response.put("description", "用户不存在");
        }
        return response;
    }

    @ResponseBody
    @RequestMapping(value = "/byUserName", method = RequestMethod.POST)
    public Map<String, Object> findByUserName(String userName, HttpSession session, HttpServletRequest request) {
        UserEntity user = null;
        Map<String, Object> response = new HashMap<String, Object>();
        String userId = (String) session.getAttribute("SID");
        if (StringUtils.isBlank(userId)) {
            response.put("status", "refuse");
            response.put("description", "未登录");
            return response;
        }
        user = userServie.findByUserName(userName);
        if (null != user) {
            user.setPassword("********");
            response.put("status", "ok");
            response.put("body", user);
        } else {
            response.put("status", "error");
            response.put("description", "用户不存在");
        }
        return response;
    }

    @ResponseBody
    @RequestMapping(value = "/byAdmin", method = RequestMethod.POST)
    public Map<String, Object> findUsersAll(HttpSession session, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        response = userServie.findUsersAll();

        return response;
    }

    //通过ID查找用户信息
    @ResponseBody
    @RequestMapping(value = "/byUserId", method = RequestMethod.POST)
    public Map<String, Object> findByUserId(UserEntity userEntity, HttpSession session, HttpServletRequest request) {
        UserEntity user = null;
        Map<String, Object> response = new HashMap<String, Object>();

        user = userServie.findByUserId(userEntity.getId());
        if (null != user) {
            user.setPassword("********");
            response.put("status", "ok");
            response.put("body", user);
        } else {
            response.put("status", "error");
            response.put("description", "用户不存在");
        }
        return response;
    }

    @ResponseBody
    @RequestMapping(value = "/updateUserByAdmin", method = RequestMethod.POST)
    public Map<String, Object> updateUserByAdmin(UserEntity userEntity, HttpSession session, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<String, Object>();
        UserEntity user = null;
        String userId = userEntity.getId();
        user = userServie.findById(userId);
        if (userServie.checkUser(user)) {
            response.put("status", "empty");
            response.put("description", "用户不存在");
            return response;
        }
        userEntity.setPassword(user.getPassword());
        userEntity.setStatus(user.getStatus());
        int status = userServie.updateUserByAdmin(userEntity);
        if (status == STATUS.SUCCESS) {
            response.put("status", "ok");
            response.put("description", "修改成功");
        } else if (status == STATUS.FORMAT_ERROR) {
            response.put("status", "error");
            response.put("description", "填写信息格式错误");
        }
        return response;
    }


    //删除只是禁用用户，将用户status改为0
    @ResponseBody
    @RequestMapping(value = "/deleteByUserID", method = RequestMethod.POST)
    public Map<String, Object> deleteByUserId(UserEntity userEntity, HttpSession session, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<String, Object>();
        UserEntity user = null;
        String userId = userEntity.getId();
        user = userServie.findById(userId);
        if (userServie.checkUser(user)) {
            response.put("status", "empty");
            response.put("description", "用户不存在");
            return response;
        }

        user.setStatus("0");
        int status = userServie.updateUserByAdmin(user);
        if (status == STATUS.SUCCESS) {
            response.put("status", "ok");
            response.put("description", "删除成功");
        } else if (status == STATUS.FORMAT_ERROR) {
            response.put("status", "error");
            response.put("description", "删除失败");
        }

        return response;
    }

    @ResponseBody
    @RequestMapping(value = "/reqByAdmin", method = RequestMethod.POST)
    public Map<String, Object> findReqUsersAll(UserEntity userEntity, HttpSession session, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();

        response = userServie.findReqUsersAll(userEntity);

        return response;
    }

    //通过管理员修改密码
    @ResponseBody
    @RequestMapping(value = "/changePassByAdmin", method = RequestMethod.POST)
    public Map<String, Object> changePassByAdmin( String userId, String newPassword,HttpSession session, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();

        BigDecimal db = new BigDecimal(userId);
        userId = db.toPlainString();

        if (StringUtils.isBlank(userId)) {
            response.put("status", "refuse");
            response.put("description", "未登录");
            return response;
        }
        UserEntity check = new UserEntity();
        check.setId(userId);
        if (userServie.checkUser(check)) {
            response.put("status", "empty");
            response.put("description", "用户不存在");
            return response;
        }
        int status = userServie.changePassByAdmin(userId, newPassword);
        if (status == STATUS.SUCCESS) {
            response.put("status", "ok");
            response.put("description", "修改密码成功");
        } else {
            response.put("status", "fail");
            response.put("description", "修改失败");
        }
        return response;
    }

}